package com.example.elmmerchants.Product_Management;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.elmmerchants.R;
import com.example.elmmerchants.SQL.Connection_SQL;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.io.ByteArrayOutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Update_Product_Data_Page extends AppCompatActivity {

    EditText product_name_edit_text, set_product_price, weight, set_inventory, min_purchase;
    ImageView show_image;
    LinearLayout product_image, not_set_image, specification_view, attributes_item, update;
    TextView which_category, has_set_specification, code, how_many_attributes_text_view, delete;
    RelativeLayout set_category, set_scan_code, setting_specification, set_product_attributes;
    Switch is_open_auto_re_inventory, is_single_order_without_delivery;

    String product_name, product_category, specification_name, specification_data, barcode, product_price, product_inventory, is_auto_return_inventory, product_weight, attributes_name, attributes_label, email, category_text, is_single_order_without_delivery_text, min_purchase_text;
    byte[] product_pic;
    Uri image1;
    int choose_how_many_category = 0, how_many_specification = 0, how_many_attributes = 0;
    Map<String, Integer> category = new HashMap<>();
    ArrayList<String> specification = new ArrayList<>();
    ArrayList<String> attributes = new ArrayList<>();
    boolean is_finish_find = false, is_this_bar_code = false, is_finish_upload = false, is_finish_loading_image = false, is_delete_product = false;
    String name;
    int weight_number, get_how_many_attributes = 0;
    double price;
    AlertDialog dialog;

    private final ActivityResultLauncher<Intent> id_card_activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult o) {
            if (o.getResultCode() == RESULT_OK) {
                if (o.getData() != null) {
                    image1 = o.getData().getData();

                    try {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), image1);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        product_pic = baos.toByteArray();

                        show_image.setVisibility(View.VISIBLE);
                        not_set_image.setVisibility(View.GONE);
                        show_image.setImageBitmap(bitmap);

                    } catch (Exception e) {
                    }
                }
            }
            else {
                Toast.makeText(Update_Product_Data_Page.this, "请选择图片", Toast.LENGTH_SHORT).show();
            }
        }
    });

    private class Loading_Category_Thread extends Thread {
        @Override
        public void run() {
            String temp = "";
            for (int i = 0; i < category_text.length(); i++) {
                if (category_text.charAt(i) == ',') {
                    if (!temp.equals("全部")) {
                        category.put(temp, 0);
                    }
                    temp = "";
                }
                else {
                    temp += category_text.charAt(i);
                }
            }

            temp = "";
            for (int i = 0; i < product_category.length(); i++) {
                if (product_category.charAt(i) == ',') {
                    category.replace(temp, 1);
                    temp = "";
                }
                else {
                    temp += product_category.charAt(i);
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    set_category.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            choose_how_many_category = 0;
                            Dialog dialog1 = new Dialog(view.getContext());
                            dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
                            dialog1.setContentView(R.layout.set_category_bottom_dialog);
                            LinearLayout category_item = dialog1.findViewById(R.id.category_item);
                            TextView how_many_category = dialog1.findViewById(R.id.how_many_category);
                            LinearLayout ok_button = dialog1.findViewById(R.id.ok_button);
                            TextView button_text = dialog1.findViewById(R.id.button_text);
                            EditText search = dialog1.findViewById(R.id.search);
                            ImageView close = dialog1.findViewById(R.id.close);
                            close.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    dialog1.dismiss();
                                }
                            });

                            search.addTextChangedListener(new TextWatcher() {
                                @Override
                                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                                }

                                @Override
                                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                                }

                                @Override
                                public void afterTextChanged(Editable editable) {
                                    category_item.removeAllViews();
                                    if (search.getText().length() == 0) {
                                        for (String key : category.keySet()) {
                                            View view1 = LayoutInflater.from(view.getContext()).inflate(R.layout.choose_category_view, null);
                                            CheckBox item = view1.findViewById(R.id.item);
                                            item.setText(key);
                                            if (category.get(key) == 1) {
                                                item.setChecked(true);
                                            }
                                            else {
                                                item.setChecked(false);
                                            }
                                            item.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View view) {
                                                    if (item.isChecked() && choose_how_many_category >= 5) {
                                                        item.setChecked(false);
                                                        Toast.makeText(Update_Product_Data_Page.this, "最多只可选择5个", Toast.LENGTH_SHORT).show();
                                                    }
                                                    else if (item.isChecked()) {
                                                        choose_how_many_category += 1;
                                                        category.replace(key, 1);
                                                    }
                                                    else {
                                                        choose_how_many_category -= 1;
                                                        category.replace(key, 0);
                                                    }
                                                    how_many_category.setText(String.valueOf(choose_how_many_category));
                                                    if (choose_how_many_category >= 1) {
                                                        ok_button.setBackgroundResource(R.drawable.border_yellow_5dp);
                                                        button_text.setTextColor(Color.BLACK);
                                                    }
                                                    else if (choose_how_many_category == 0) {
                                                        ok_button.setBackgroundResource(R.drawable.border_light_gray);
                                                        button_text.setTextColor(Color.WHITE);
                                                    }
                                                }
                                            });
                                            category_item.addView(view1);
                                        }
                                    }
                                    else {
                                        for (String key : category.keySet()) {
                                            if (key.indexOf(search.getText().toString()) != -1) {
                                                View view1 = LayoutInflater.from(view.getContext()).inflate(R.layout.choose_category_view, null);
                                                CheckBox item = view1.findViewById(R.id.item);
                                                item.setText(key);
                                                if (category.get(key) == 1) {
                                                    item.setChecked(true);
                                                }
                                                else {
                                                    item.setChecked(false);
                                                }
                                                item.setOnClickListener(new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View view) {
                                                        if (item.isChecked() && choose_how_many_category >= 5) {
                                                            item.setChecked(false);
                                                            Toast.makeText(Update_Product_Data_Page.this, "最多只可选择5个", Toast.LENGTH_SHORT).show();
                                                        }
                                                        else if (item.isChecked()) {
                                                            choose_how_many_category += 1;
                                                            category.replace(key, 1);
                                                        }
                                                        else {
                                                            choose_how_many_category -= 1;
                                                            category.replace(key, 0);
                                                        }
                                                        how_many_category.setText(String.valueOf(choose_how_many_category));
                                                        if (choose_how_many_category >= 1) {
                                                            ok_button.setBackgroundResource(R.drawable.border_yellow_5dp);
                                                            button_text.setTextColor(Color.BLACK);
                                                        }
                                                        else if (choose_how_many_category == 0) {
                                                            ok_button.setBackgroundResource(R.drawable.border_light_gray);
                                                            button_text.setTextColor(Color.WHITE);
                                                        }
                                                    }
                                                });
                                                category_item.addView(view1);
                                            }
                                        }
                                    }
                                }
                            });

                            for (String key : category.keySet()) {
                                View view1 = LayoutInflater.from(view.getContext()).inflate(R.layout.choose_category_view, null);
                                CheckBox item = view1.findViewById(R.id.item);
                                item.setText(key);
                                if (category.get(key) == 1) {
                                    item.setChecked(true);
                                    choose_how_many_category += 1;
                                }
                                else {
                                    item.setChecked(false);
                                }
                                item.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        if (item.isChecked() && choose_how_many_category >= 5) {
                                            item.setChecked(false);
                                            Toast.makeText(Update_Product_Data_Page.this, "最多只可选择5个", Toast.LENGTH_SHORT).show();
                                        }
                                        else if (item.isChecked()) {
                                            choose_how_many_category += 1;
                                            category.replace(key, 1);
                                        }
                                        else {
                                            choose_how_many_category -= 1;
                                            category.replace(key, 0);
                                        }
                                        how_many_category.setText(String.valueOf(choose_how_many_category));
                                        if (choose_how_many_category >= 1) {
                                            ok_button.setBackgroundResource(R.drawable.border_yellow_5dp);
                                            button_text.setTextColor(Color.BLACK);
                                        }
                                        else if (choose_how_many_category == 0) {
                                            ok_button.setBackgroundResource(R.drawable.border_light_gray);
                                            button_text.setTextColor(Color.WHITE);
                                        }
                                    }
                                });
                                category_item.addView(view1);
                            }
                            how_many_category.setText(String.valueOf(choose_how_many_category));
                            if (choose_how_many_category >= 1) {
                                ok_button.setBackgroundResource(R.drawable.border_yellow_5dp);
                                button_text.setTextColor(Color.BLACK);
                            }
                            else if (choose_how_many_category == 0) {
                                ok_button.setBackgroundResource(R.drawable.border_light_gray);
                                button_text.setTextColor(Color.WHITE);
                            }
                            ok_button.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (choose_how_many_category > 0) {
                                        String choose_which_category = "";
                                        for (String key : category.keySet()) {
                                            if (category.get(key) == 1) {
                                                choose_which_category += key;
                                                choose_which_category += ",";
                                            }
                                        }
                                        which_category.setText(choose_which_category);
                                        dialog1.dismiss();
                                    }
                                    else {
                                        Toast.makeText(Update_Product_Data_Page.this, "请选择分类", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });

                            dialog1.show();
                            dialog1.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, 1500);
                            dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                            dialog1.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
                            dialog1.getWindow().setGravity(Gravity.BOTTOM);
                        }
                    });
                }
            });
        }
    }

    private class Loading_Specification_Thread extends Thread {
        @Override
        public void run() {
            String specification_name_temp = "";
            int temp_j = 0;
            for (int i = 0; i < specification_name.length(); i++) {
                if (specification_name.charAt(i) == ',') {
                    how_many_specification += 1;
                    specification.add(specification_name_temp);
                    specification_name_temp = "";
                    String specification_data_temp = "";
                    for (int j = temp_j; j < specification_data.length(); j++) {
                        if (specification_data_temp.equals("规格数据已添加")) {
                            temp_j = j + 1;
                            break;
                        }
                        else if (specification_data.charAt(j) == ',') {
                            specification.add(specification_data_temp);
                            specification_data_temp = "";
                        }
                        else {
                            specification_data_temp += specification_data.charAt(j);
                        }
                    }
                }
                else {
                    specification_name_temp += specification_name.charAt(i);
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (how_many_specification > 0) {
                        for (int i = 0; i < specification.size(); i += 6) {
                            View view = LayoutInflater.from(Update_Product_Data_Page.this).inflate(R.layout.show_specification_card_view, null);
                            TextView specification_name = view.findViewById(R.id.specification_name);
                            specification_name.setText(specification.get(i));
                            TextView specification_price = view.findViewById(R.id.specification_price);
                            specification_price.setText(specification.get(i + 1));
                            TextView specification_inventory = view.findViewById(R.id.specification_inventory);
                            specification_inventory.setText(specification.get(i + 2));
                            TextView specification_weight = view.findViewById(R.id.specification_weight);
                            specification_weight.setText(specification.get(i + 5));
                            specification_view.addView(view);
                        }
                        has_set_specification.setText("共" + how_many_specification + "规格");
                    }
                    else {
                        has_set_specification.setText("请设置");
                        specification_view.removeAllViews();
                    }
                }
            });
        }
    }

    private class Loading_Attributes_Thread extends Thread {
        @Override
        public void run() {
            String attributes_name_temp = "";
            int temp_j = 0;
            for (int i = 0; i < attributes_name.length(); i++) {
                if (attributes_name.charAt(i) == ',') {
                    how_many_attributes += 1;
                    attributes.add(attributes_name_temp);
                    attributes_name_temp = "";
                    String attributes_label_temp = "";
                    for (int j = temp_j; j < attributes_label.length(); j++) {
                        if (attributes_label_temp.equals("属性添加完毕")) {
                            temp_j = j + 1;
                            attributes.add("属性添加完毕");
                            break;
                        }
                        else if (attributes_label.charAt(j) == ',') {
                            attributes.add(attributes_label_temp);
                            attributes_label_temp = "";
                        }
                        else {
                            attributes_label_temp += attributes_label.charAt(j);
                        }
                    }
                }
                else {
                    attributes_name_temp += attributes_name.charAt(i);
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (how_many_attributes > 0) {
                        int j = 0;
                        View view = LayoutInflater.from(Update_Product_Data_Page.this).inflate(R.layout.show_attributes_card_view, null);
                        LinearLayout label_item = view.findViewById(R.id.label_item);
                        for (int i = 0; i < attributes.size(); i++) {
                            if (j == 0) {
                                TextView attributes_name = view.findViewById(R.id.attributes_name);
                                attributes_name.setText(attributes.get(i));
                                j = 1;
                            }
                            else if (attributes.get(i).equals("属性添加完毕")) {
                                attributes_item.addView(view);
                                view = LayoutInflater.from(Update_Product_Data_Page.this).inflate(R.layout.show_attributes_card_view, null);
                                label_item = view.findViewById(R.id.label_item);
                                j = 0;
                            }
                            else {
                                View view1 = LayoutInflater.from(Update_Product_Data_Page.this).inflate(R.layout.show_label_card_view, null);
                                TextView label_name = view1.findViewById(R.id.label_name);
                                label_name.setText(attributes.get(i));
                                label_item.addView(view1);
                            }
                        }
                        how_many_attributes_text_view.setText("共" + how_many_attributes + "属性");
                    }
                    else {
                        how_many_attributes_text_view.setText("请设置");
                        attributes_item.removeAllViews();
                    }
                }
            });
        }
    }

    private class Loading_BarCode_Thread extends Thread {

        IntentResult intentResult;

        public Loading_BarCode_Thread(IntentResult intentResult) {
            this.intentResult = intentResult;
        }

        @Override
        public void run() {
            is_finish_find = false;
            is_this_bar_code = false;
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM bar_code_data WHERE bar_code = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, intentResult.getContents());
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        name = set.getString("name");
                        price = set.getDouble("price");
                        weight_number = set.getInt("weight");
                        product_pic = set.getBytes("pic");
                        is_this_bar_code = true;
                    }
                    is_finish_find = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_finish_find) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (is_this_bar_code) {
                        code.setText(intentResult.getContents());
                        product_name_edit_text.setText(name);
                        set_product_price.setText(String.valueOf(price));
                        weight.setText(String.valueOf(weight_number));
                        Bitmap bitmap = BitmapFactory.decodeByteArray(product_pic, 0, product_pic.length);
                        show_image.setImageBitmap(bitmap);
                    }
                    else {
                        code.setText(intentResult.getContents());
                    }
                }
            });
        }
    }

    private class Update_Data_Thread extends Thread {
        @Override
        public void run() {
            specification_name = "";
            specification_data = "";
            attributes_name = "";
            attributes_label = "";
            if (how_many_specification > 0) {
                for (int j = 0; j < specification.size(); j += 6) {
                    specification_name += specification.get(j);
                    specification_name += ",";
                    specification_data += specification.get(j + 1);
                    specification_data += ",";
                    specification_data += specification.get(j + 2);
                    specification_data += ",";
                    specification_data += specification.get(j + 3);
                    specification_data += ",";
                    specification_data += specification.get(j + 4);
                    specification_data += ",";
                    specification_data += specification.get(j + 5);
                    specification_data += ",";
                    specification_data += "规格数据已添加";
                    specification_data += ",";
                }
            }
            if (get_how_many_attributes > 0) {
                int k = 0;
                for (int j = 0; j < attributes.size(); j++) {
                    if (k == 0) {
                        attributes_name += attributes.get(j);
                        attributes_name += ",";
                        k = 1;
                    }
                    else if (attributes.get(j).equals("属性添加完毕")) {
                        attributes_label += "属性添加完毕";
                        attributes_label += ",";
                        k = 0;
                    }
                    else {
                        attributes_label += attributes.get(j);
                        attributes_label += ",";
                    }
                }
            }

            is_finish_upload = false;
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    Blob blobUpload = connection.createBlob();
                    blobUpload.setBytes(1, product_pic);
                    String sql = "update `elm`.`" + email + "_merchant_product` set inventory = ?, name = ?, picture = ?, is_single_order_without_delivery = ?, product_price = ?, is_auto_return_inventory = ?, weight = ?, description = ?, barcode = ?, category_1 = ?, category_2 = ?, category_3 = ?, category_4 = ?, category_5 = ?, specification_name = ?, specification_data = ?, attributes_name = ?, attributes_label = ?, min_purchase = ? WHERE name = ?";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, set_inventory.getText().toString());
                    preparedStatement.setString(2, product_name_edit_text.getText().toString());
                    preparedStatement.setBlob(3, blobUpload);
                    if (is_single_order_without_delivery.isChecked()) {
                        preparedStatement.setInt(4, 1);
                    }
                    else {
                        preparedStatement.setInt(4, 0);
                    }
                    preparedStatement.setDouble(5, Double.parseDouble(set_product_price.getText().toString()));
                    if (is_open_auto_re_inventory.isChecked()) {
                        preparedStatement.setInt(6, 1);
                    }
                    else {
                        preparedStatement.setInt(6, 0);
                    }
                    preparedStatement.setInt(7, Integer.parseInt(weight.getText().toString()));
                    preparedStatement.setString(8, "");
                    preparedStatement.setString(9, code.getText().toString());
                    int i = 10;

                    for (String key : category.keySet()) {
                        if (category.get(key) == 1) {
                            preparedStatement.setString(i, key);
                            i += 1;
                        }
                    }
                    for (int j = i; j <= 14; j++) {
                        preparedStatement.setString(j, "");
                    }
                    preparedStatement.setString(15, specification_name);
                    preparedStatement.setString(16, specification_data);
                    preparedStatement.setString(17, attributes_name);
                    preparedStatement.setString(18, attributes_label);
                    preparedStatement.setInt(19, Integer.parseInt(min_purchase.getText().toString()));
                    preparedStatement.setString(20, product_name);
                    preparedStatement.executeUpdate();

                    if (!is_this_bar_code && !code.getText().toString().equals("扫码可快速获取商品信息")) {
                        String sql2 = "insert into `elm`.`bar_code_data` (bar_code, name, price, pic, weight) VALUES (?, ?, ?, ?, ?)";
                        PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
                        preparedStatement2.setString(1, code.getText().toString());
                        preparedStatement2.setString(2, product_name_edit_text.getText().toString());
                        preparedStatement2.setDouble(3, Double.parseDouble(set_product_price.getText().toString()));
                        preparedStatement2.setBlob(4, blobUpload);
                        preparedStatement2.setInt(5, Integer.parseInt(weight.getText().toString()));
                        preparedStatement2.executeUpdate();
                    }

                    is_finish_upload = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_finish_upload) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();
                    Intent intent = new Intent(Update_Product_Data_Page.this, Shop_Management_Page.class);
                    setResult(1, intent);
                    finish();
                }
            });
        }
    }

    private class Loading_Image_Thread extends Thread {

        String product_name;

        public Loading_Image_Thread(String product_name) {
            this.product_name = product_name;
        }

        @Override
        public void run() {
            is_finish_loading_image = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql2 = "SELECT * FROM `" + email + "_merchant_product` where name = ?;";
                    PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
                    preparedStatement2.setString(1, product_name);
                    ResultSet set2 = preparedStatement2.executeQuery();
                    while (set2.next()) {
                        product_pic = set2.getBytes("picture");
                    }
                    is_finish_loading_image = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_finish_loading_image) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Bitmap decodedImage = BitmapFactory.decodeByteArray(product_pic, 0, product_pic.length);
                    show_image.setImageBitmap(decodedImage);
                }
            });
        }
    }

    private class Delete_Product_Thread extends Thread {

        String product_name;

        public Delete_Product_Thread(String product_name) {
            this.product_name = product_name;
        }
        @Override
        public void run() {
            is_delete_product = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "DELETE FROM `elm`.`" + email + "_merchant_product` WHERE name = ?";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, product_name);
                    preparedStatement.executeUpdate();
                    is_delete_product = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_delete_product) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();
                    Intent intent = new Intent(Update_Product_Data_Page.this, Shop_Management_Page.class);
                    setResult(1, intent);
                    finish();
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_product_data_page);

        email = getIntent().getStringExtra("email");
        category_text = getIntent().getStringExtra("category_text");
        product_name = getIntent().getStringExtra("product_name");
        product_category = getIntent().getStringExtra("product_category");
        specification_name = getIntent().getStringExtra("specification_name");
        specification_data = getIntent().getStringExtra("specification_data");
        barcode = getIntent().getStringExtra("barcode");
        product_price = getIntent().getStringExtra("product_price");
        product_inventory = getIntent().getStringExtra("product_inventory");
        is_auto_return_inventory = getIntent().getStringExtra("is_auto_return_inventory");
        product_weight = getIntent().getStringExtra("product_weight");
        attributes_name = getIntent().getStringExtra("attributes_name");
        attributes_label = getIntent().getStringExtra("attributes_label");
        is_single_order_without_delivery_text = getIntent().getStringExtra("is_single_order_without_delivery");
        min_purchase_text = getIntent().getStringExtra("min_purchase");

        product_name_edit_text = findViewById(R.id.product_name);
        product_name_edit_text.setText(product_name);
        show_image = findViewById(R.id.show_image);
        not_set_image = findViewById(R.id.not_set_image);
        product_image = findViewById(R.id.product_image);
        which_category = findViewById(R.id.which_category);
        set_category = findViewById(R.id.set_category);
        has_set_specification = findViewById(R.id.has_set_specification);
        specification_view = findViewById(R.id.specification_view);
        code = findViewById(R.id.code);
        set_scan_code = findViewById(R.id.set_scan_code);
        set_product_price = findViewById(R.id.set_product_price);
        weight = findViewById(R.id.weight);
        set_inventory = findViewById(R.id.set_inventory);
        is_open_auto_re_inventory = findViewById(R.id.is_open_auto_re_inventory);
        how_many_attributes_text_view = findViewById(R.id.how_many_attributes);
        attributes_item = findViewById(R.id.attributes_item);
        setting_specification = findViewById(R.id.setting_specification);
        set_product_attributes = findViewById(R.id.set_product_attributes);
        update = findViewById(R.id.update);
        delete = findViewById(R.id.delete);
        min_purchase = findViewById(R.id.min_purchase);
        is_single_order_without_delivery = findViewById(R.id.is_single_order_without_delivery);

        code.setText(barcode);
        set_product_price.setText(product_price);
        weight.setText(product_weight);
        set_inventory.setText(product_inventory);
        min_purchase.setText(min_purchase_text);
        if (is_auto_return_inventory.equals("1")) {
            is_open_auto_re_inventory.setChecked(true);
        }
        else {
            is_open_auto_re_inventory.setChecked(false);
        }

        if (is_single_order_without_delivery_text.equals("1")) {
            is_single_order_without_delivery.setChecked(true);
        }
        else {
            is_single_order_without_delivery.setChecked(false);
        }

        product_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                id_card_activityResultLauncher.launch(intent);
            }
        });

        which_category.setText(product_category);

        Loading_Image_Thread loadingImageThread = new Loading_Image_Thread(product_name);
        loadingImageThread.start();

        Loading_Category_Thread loadingCategoryThread = new Loading_Category_Thread();
        loadingCategoryThread.start();

        Loading_Specification_Thread loadingSpecificationThread = new Loading_Specification_Thread();
        loadingSpecificationThread.start();

        Loading_Attributes_Thread loadingAttributesThread = new Loading_Attributes_Thread();
        loadingAttributesThread.start();

        set_scan_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                IntentIntegrator intentIntegrator = new IntentIntegrator((Activity) view.getContext());
                intentIntegrator.setPrompt("扫描条形码");
                intentIntegrator.setOrientationLocked(true);
                intentIntegrator.initiateScan();
            }
        });

        setting_specification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Update_Product_Data_Page.this, Update_Specification_Page.class);
                intent.putExtra("specification", specification);
                startActivityForResult(intent, 1);
            }
        });

        set_product_attributes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Update_Product_Data_Page.this, Update_Attributes_Page.class);
                intent.putExtra("attributes", attributes);
                startActivityForResult(intent, 2);
            }
        });

        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                set_dialog();
                Update_Data_Thread updateDataThread = new Update_Data_Thread();
                updateDataThread.start();
            }
        });

        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                builder.setCancelable(false);
                builder.setTitle("是否刪除");
                builder.setMessage("是否刪除该产品");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        set_dialog();
                        Delete_Product_Thread deleteProductThread = new Delete_Product_Thread(product_name);
                        deleteProductThread.start();
                    }
                });

                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });

                builder.create();
                builder.show();
            }
        });
    }

    public void set_dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater1 = LayoutInflater.from(this);
        builder.setView(inflater1.inflate(R.layout.loading, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (intentResult != null) {
            if (intentResult.getContents() == null) {
                Toast.makeText(getBaseContext(), "未添加条形码", Toast.LENGTH_SHORT).show();
            } else {
                Loading_BarCode_Thread loadingBarCodeThread = new Loading_BarCode_Thread(intentResult);
                loadingBarCodeThread.start();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }

        switch (requestCode) {
            case 1: {
                if (data != null) {
                    specification_view.removeAllViews();
                    how_many_specification = 0;
                    specification = data.getStringArrayListExtra("specification_data");
                    for (int i = 0; i < specification.size(); i += 6) {
                        how_many_specification += 1;
                        View view = LayoutInflater.from(this).inflate(R.layout.show_specification_card_view, null);
                        TextView specification_name = view.findViewById(R.id.specification_name);
                        specification_name.setText(specification.get(i));
                        TextView specification_price = view.findViewById(R.id.specification_price);
                        specification_price.setText(specification.get(i + 1));
                        TextView specification_inventory = view.findViewById(R.id.specification_inventory);
                        specification_inventory.setText(specification.get(i + 2));
                        TextView specification_weight = view.findViewById(R.id.specification_weight);
                        specification_weight.setText(specification.get(i + 3));
                        specification_view.addView(view);
                    }
                    if (how_many_specification > 0) {
                        has_set_specification.setText("共" + how_many_specification + "规格");
                    }
                    else {
                        has_set_specification.setText("请设置");
                    }
                }
                break;
            }

            case 2: {
                if (data != null) {
                    get_how_many_attributes = 0;
                    attributes_item.removeAllViews();
                    attributes = data.getStringArrayListExtra("attributes");
                    int j = 0;
                    View view = LayoutInflater.from(this).inflate(R.layout.show_attributes_card_view, null);
                    LinearLayout label_item = view.findViewById(R.id.label_item);
                    for (int i = 0; i < attributes.size(); i++) {
                        if (j == 0) {
                            TextView attributes_name = view.findViewById(R.id.attributes_name);
                            attributes_name.setText(attributes.get(i));
                            j = 1;
                            get_how_many_attributes += 1;
                        }
                        else if (attributes.get(i).equals("属性添加完毕")) {
                            attributes_item.addView(view);
                            view = LayoutInflater.from(this).inflate(R.layout.show_attributes_card_view, null);
                            label_item = view.findViewById(R.id.label_item);
                            j = 0;
                        }
                        else {
                            View view1 = LayoutInflater.from(this).inflate(R.layout.show_label_card_view, null);
                            TextView label_name = view1.findViewById(R.id.label_name);
                            label_name.setText(attributes.get(i));
                            label_item.addView(view1);
                        }
                    }
                    if (get_how_many_attributes > 0) {
                        how_many_attributes_text_view.setText("共" + get_how_many_attributes + "属性");
                    }
                    else {
                        how_many_attributes_text_view.setText("可设置如”温度: 常温、冰冻”");
                    }
                }
                break;
            }
        }
    }
}